package com.lagou.ModelTest4.Second;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Set;
import java.util.TreeSet;

public class ServerStringTest {
    public static void main(String[] args) {
        ServerSocket ss= null;
        Socket s= null;
        PrintStream ps=null;

        try {
            //1.构造ServerSocket类型的对象还有端口号
            ss = new ServerSocket(6666);
            //2.等待客户端请求连接
            System.out.println("等待客户端的请求...");
            s = ss.accept();
            System.out.println("客户端"+s.getInetAddress()+"连接成功!");
            //3.输入输出流 循环接收客户端发来的信息
            //把获取到的集合传入abc.txt中
            ps=new PrintStream(new FileOutputStream("D:/abc.txt"));
            while(true){
                BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
                String str1=br.readLine();
                System.out.println("客户端发来的信息是:"+str1);
                ps.println(str1);
                if("end".equalsIgnoreCase(str1)){
                    System.out.println("Over!");
                    break;
                }
                //System.out.println("获取到的信息集合为:"+s1);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        //4.关闭并释放有关资源
            if(null!=s) {
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null!=ss) {
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null!=ps){
                    ps.close();
                }
            }
        }
    }
